<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      title="转为采购单"
      :btn-list="fullInfo.btnList"
    >
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- form -->
          <PageForm
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :disabled="formInfo.disabled"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
          >
            <template v-slot:form-deptName>
              <el-input
                v-if="isSpecialEdit === 1"
                v-model="formInfo.data.deptName"
                disabled
              ></el-input>
              <el-input
                v-else
                v-model="formInfo.data.deptName"
                class="not-mongolia"
                type="input"
                :disabled="true"
                placeholder="请选择部门"
              >
                <template #append>
                  <el-icon @click="openDeptWindow"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
            <template v-slot:form-receiveAddressValue>
              <el-input
                v-if="isSpecialEdit === 1"
                v-model="formInfo.data.receiveAddressValue"
                disabled
              ></el-input>
              <el-input
                v-else
                v-model="formInfo.data.receiveAddressValue"
                class="not-mongolia"
                type="input"
                :disabled="true"
                placeholder="请选择收货地址"
              >
                <template #append>
                  <el-icon @click="openReceiveAddressWindow"
                    ><MoreFilled
                  /></el-icon>
                </template>
              </el-input>
            </template>
          </PageForm>
        </div>
      </div>

      <div class="model-panel">
        <div class="model-panel-title">
          <Tooltip :text="$t('detailInfo')" />
          <div class="model-tips">
            (证照：<span>近效期</span>
            <span class="model-tips-nearly"></span>
          </div>
          <div class="model-tips">
            <span>过期</span>
            <span class="model-tips-expire"></span>)
          </div>
        </div>
        <div class="model-panel-body">
          <!-- 条件栏 -->
          <PageFilter
            v-if="!isReadOnly"
            v-model:query="filterInfo.query"
            :filter-list="filterInfo.list"
          >
            <template v-slot:filter-addProduct>
              <el-button :disabled="!canAddProduct" @click="addProduct"
                >添加产品</el-button
              >
            </template>
            <template v-slot:filter-removeProduct>
              <el-button :disabled="!canRemoveProduct" @click="removeProduct()"
                >删除产品</el-button
              >
            </template>
            <template v-slot:filter-selectTemplate>
              <el-button
                :disabled="!formInfo.data.deptId || isSpecialEdit === 1"
                @click="selectTemplate"
                >选择模板</el-button
              >
            </template>
          </PageFilter>
          <div class="flex_full_item">
            <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
              <!-- 表格 -->
              <PageTable
                class="table-scroll-hidden"
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :summary-field-list="tableInfo.summaryFieldList"
                :tab-index="false"
                v-model:query="filterInfo.query"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :row-class-name="tableRowClassName"
                @handleEvent="handleEvent"
              >
                <template v-slot:col-qty="scope">
                  <el-form-item class="margin-bottom">
                    <div class="page-table-input-number-wrapper">
                      <div class="page-table-input-number-left">
                        <div class="page-table-input-number-item">
                          <el-form-item
                            :prop="`data.${scope.$index}.largeUnitQty`"
                            :rules="
                              scope.$index >= 0
                                ? [
                                    {
                                      validator: $validate.positiveAndZero,
                                      trigger: 'blur',
                                    },
                                  ]
                                : []
                            "
                          >
                            <el-input-number
                              style="width: 100%; margintop: 18px"
                              v-model.lazy="scope.row.largeUnitQty"
                              clearable
                              controls-position="right"
                              :precision="
                                scope.row.qtyOperateMode === 0 ||
                                scope.row.qtyOperateMode === 2
                                  ? 0
                                  : systemConfig.qty_show_precision
                              "
                              @change="
                                changeLarge(
                                  $event,
                                  `data.${scope.$index}.largeUnitQty`
                                )
                              "
                              :min="0"
                              :max="largeMax(scope.row)"
                            />
                          </el-form-item>
                          <div class="page-table-input-number-item-unite">
                            {{ scope.row.unitName }}
                          </div>
                        </div>
                        <div
                          class="page-table-input-number-item"
                          v-if="
                            scope.row.unitConvertCoefficient > 1 &&
                            scope.row.qtyOperateMode === 2
                          "
                        >
                          <el-form-item>
                            <el-input-number
                              style="width: 100%; margintop: 18px"
                              v-model.lazy="scope.row.smallUnitQty"
                              clearable
                              controls-position="right"
                              :precision="0"
                              :min="0"
                              :max="smallMax(scope.row)"
                            />
                          </el-form-item>
                          <div class="page-table-input-number-item-unite">
                            {{ scope.row.calcUnitName }}
                          </div>
                        </div>
                      </div>
                      <div
                        class="page-table-input-number-right"
                        v-if="scope.row.qtyOperateMode === 2"
                      >
                        {{ $fn.qtyFormatter(scope.row.qty) }}
                      </div>
                    </div>
                  </el-form-item>
                </template>
                <template v-slot:col-price="scope">
                  <p>{{ scope.row.price }}</p>
                  <p
                    style="color: red"
                    v-if="
                      scope.row.isLimitPrice == 1 &&
                      scope.row.price > scope.row.purchaseLimitPrice
                    "
                  >
                    超过产品限价:{{ scope.row.purchaseLimitPrice }}
                  </p>
                </template>
              </PageTable>
            </el-form>
          </div>

          <!-- 选择产品 -->
          <NewSelectProduct
            v-if="productInfo.visible"
            v-model:show-dialog="productInfo.visible"
            v-model:query="productInfo.query.queryMap"
            :query-params="productInfo.query.queryParams"
            :api="productInfo.api"
            :notDefaultProductSupplier="true"
            :table-key="productInfo.tableKey"
            @callback="selectProductCallback"
          />

          <!-- 在供货目录中 根据产品选择供应商 -->
          <SelectSupplier
            v-if="selectProductSupplier.visible"
            v-model:show-dialog="selectProductSupplier.visible"
            v-model:query="selectProductSupplier.query"
            :check-box="false"
            :highlight-row="true"
            :api="selectProductSupplier.api"
            @callback="selectProductSupplierCallback"
          />
          <!-- 选择收货地址 -->
          <SelectReceiveAddress
            v-if="selectReceiveAddressInfo.visible"
            v-model:show-dialog="selectReceiveAddressInfo.visible"
            v-model:query="selectReceiveAddressInfo.query"
            :check-box="false"
            :highlight-row="true"
            @callback="selectReceiveAddressCallback"
          />
          <!-- 选择部门 -->
          <SelectDept
            v-if="selectDeptInfo.visible"
            v-model:show-dialog="selectDeptInfo.visible"
            v-model:query="selectDeptInfo.query"
            :check-box="false"
            :highlight-row="true"
            :saveEmpty="true"
            @callback="selectDeptCallback"
          />
          <SelectPurchTemplate
            v-if="purchTemplateInfo.visible"
            v-model:show-dialog="purchTemplateInfo.visible"
            :check-box="true"
            :tab-index="true"
            :highlight-row="false"
            v-model:query="purchTemplateInfo.query"
            @callback="selectPurchTemplateCallback"
          />
        </div>
      </div>
    </NewFullScreen>
  </div>
</template>

<script setup name="auditPurchOrderModify">
import {
  createPurchOrder,
  updatePurchOrder,
  applicationSummaryDetailAddProduct,
  getOrdersProduct,
  getPurchTemplateDetailAll,
  applicationDetailAddProduct,
} from '@/api/purch'
import { generatePurchOrderUseApplication } from '@/api/use'
import {
  getReceiveAddressPage,
  getCoreSystemConfigGetConfigValue,
  getProductCustomizeList,
  getSupplierProductPage,
} from '@/api/core'

import { getCustomizeSetting } from '@/api/customize'

const { proxy } = getCurrentInstance()
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: () => {
      return ''
    },
  },
  tableKey: {
    type: String,
    default: () => {
      return ''
    },
  },
  orderId: {
    type: [Number, String],
  },
  isSpecialEdit: {
    type: [Number, String],
  },
  useOrderNo: {
    type: [Number, String],
  },
})
const formRefs = ref([])
const purchTemplateInfo = ref({
  visible: false,
  query: {},
})
const formInfo = ref({
  ref: null,
  data: {
    deptName: '',
    deptId: '',
    supplierId: '',
    supplierName: '',
    receiveAddressValue: '',
    purchProductType: 1,
    createUserName: proxy.$store.state.user.userInfo.user
      ? proxy.$store.state.user.userInfo.user.name
      : '',
  },
  fieldList: [
    { label: '部门', value: 'deptName', type: 'slot' },
    {
      label: '创建人',
      value: 'createUserName',
      type: 'input',
      disabled: true,
    },
    { label: '收货地址', value: 'receiveAddressValue', type: 'slot' },
    {
      label: '是否寄售业务',
      value: 'isConsignBusinessValue',
      type: 'input',
      disabled: true,
      show:
        props.orderId &&
        proxy.$store.state.permission.systemConfig.is_consign_business == 1,
    },
    {
      label: '是否临采',
      value: 'temporaryPurch',
      type: 'select-model',
      code: 'default_no_or_yes',
    },
    {
      label: '是否紧急',
      value: 'isEmergency',
      type: 'select-model',
      code: 'is_emergency',
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
  rules: {
    deptName: [{ required: true, Message: '请选择部门', trigger: 'change' }],
    receiveAddressValue: [
      { required: true, Message: '请选择收货地址', trigger: 'change' },
    ],
    supplierName: [
      { required: true, Message: '请选择供应商', trigger: 'change' },
    ],
  },
  labelWidth: '120px',
})
// 过滤相关配置
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {},
  },
  list: [
    { type: 'slot', label: '添加产品', value: 'addProduct' },
    { type: 'slot', label: '删除产品', value: 'removeProduct' },
    { type: 'slot', value: 'selectTemplate' },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  selectionsCopy: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'price', show: 'false' },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
  applicationFieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '80',
    btList: [
      {
        label: '切换供应商',
        event: changeSupplier,
        ifRender: ifRenderValue,
        show: true,
      },
    ],
  },
})
const fullInfo = ref({
  btnList: [{ label: '保存', event: save, show: true }],
})
//选择产品相关
const productInfo = ref({
  visible: false,
  api: getProductCustomizeList,
  tableKey:
    'productPageForPurchOrder-com.slip.spd.entity.vo.core.CoreProductVONew',
  query: {
    queryMap: {
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: null,
      },
      status: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      supplierId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      productId: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: null,
      },
      putShelfStatus: {
        asTbName: 'core_product_new',
        columnName: 'put_shelf_status',
        queryResource: 0,
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 1,
      },
      type: {
        asTbName: 'core_product_new',
        columnName: 'type',
        queryResource: 0,
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 0,
      },
    },
    queryParams: {
      checkDeptProduct: 1,
      selectStockTotalQty: 1,
    },
  },
  searchList: [],
})
const applicationProductInfo = ref({
  visible: false,
  api: '', //产品数量不对
  query: {
    deptId: '',
  },
})
const selectSupplierInfo = ref({
  visible: false,
  query: {
    supplierAuth: 'supplierId',
  },
})
//在供货目录中 根据产品id选择供应商
const selectProductSupplier = ref({
  visible: false,
  index: '',
  api: getSupplierProductPage,
  query: {
    id: '',
    searchType: 'org',
    searchField: 'supplierId',
    supplierAuth: 'supplierId',
  },
})
const selectReceiveAddressInfo = ref({
  visible: false,
  query: {},
})
const selectDeptInfo = ref({
  visible: false,
  query: {
    deptAuth: 'id',
  },
})
const tmpData = ref([]) //用于显示取值
const showSelectOrder = ref(false)
const mergedPurchIds = ref('')
const disabledTemplateBtn = ref(false)
const defaultSelect = ref([])
const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const licencesSystemConfig = ref('')
const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    proxy.$emit('update:visible', val) // 更新父组件visible
  },
})
const isUpdate = computed(() => {
  return formInfo.value.data.id !== undefined
})
const isReadOnly = computed(() => {
  //确定是否为提交状态
  return !formInfo.value.data.status === 1
})
const canAddProduct = computed(() => {
  return formInfo.value.data.deptId && props.isSpecialEdit !== 1
})
const canRemoveProduct = computed(() => {
  return tableInfo.value.selections.length && props.isSpecialEdit !== 1
})
watch(
  () => tableInfo.value.data,
  (val) => {
    tableInfo.value.data.forEach((row) => {
      let smallUnitQty = parseFloat(row.smallUnitQty || 0)
      let unitConvertCoefficient = parseFloat(row.unitConvertCoefficient || 1)
      let largeUnitQty = parseFloat(row.largeUnitQty || 0)
      let calcQty = proxy.$fn.accAdd(
        proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
        smallUnitQty
      )
      let qty = proxy.$fn.qtyFormatter(
        proxy.$fn.accDiv(calcQty, unitConvertCoefficient)
      )
      row['calcQty'] = calcQty
      row['qty'] = qty
      row.sumAmount = proxy.$fn.accMul(
        proxy.$fn.accAdd(
          proxy.$fn.accDiv(smallUnitQty, unitConvertCoefficient),
          largeUnitQty
        ),
        parseFloat(row.price == null ? 0 : row.price)
      )
    })
  },
  { deep: true }
)

function ifRenderValue() {
  return (
    formInfo.value.data.summaryId == undefined ||
    formInfo.value.data.summaryId == '' ||
    formInfo.value.data.summaryId === -2
  )
}

function changeLarge(e, str) {
  proxy.$refs.tableForm.clearValidate(str)
}
function largeMax(row) {
  if (
    systemConfig.value.use_convert_count_restrict == 1 &&
    (row.maxConvertCount || row.maxConvertCount === 0)
  ) {
    return parseInt(row.maxConvertCount / row.unitConvertCoefficient)
  } else {
    return 99999999
  }
}
function smallMax(row) {
  if (
    systemConfig.value.use_convert_count_restrict == 1 &&
    (row.maxConvertCount || row.maxConvertCount === 0)
  ) {
    return parseInt(row.maxConvertCount % row.unitConvertCoefficient)
  } else {
    return row.unitConvertCoefficient - 1
  }
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
//切换供应商
function changeSupplier(row, index) {
  selectProductSupplier.value.visible = true
  selectProductSupplier.value.query.productId = row.productId
  selectProductSupplier.value.query.supplierIdNotIn = row.supplierId
  selectProductSupplier.value.index = index
  // selectProductSupplier.value.row = row;
}
//添加产品按钮
function addProduct() {
  let idNotIn = tableInfo.value.data.map(function (item) {
    return item.productId
  })
  let purchType = formInfo.value.data.purchType
  if (purchType === 0) {
    productInfo.value.query.queryParams.orderId = formInfo.value.data.id
    productInfo.value.tableKey =
      'purchApplicationDetailForPurchOrder-com.slip.spd.entity.vo.purch.PurchApplicationDetailVO'
    productInfo.value.api = applicationDetailAddProduct
    productInfo.value.query.queryMap.productId.value = idNotIn.toString()
    productInfo.value.query.queryMap.orderId.value =
      formInfo.value.data.applicationId
  } else if (purchType === 1) {
    productInfo.value.query.queryParams.orderId = formInfo.value.data.id
    productInfo.value.tableKey =
      'purchApplicationSummaryDetailForPurchOrder-com.slip.spd.entity.vo.purch.PurchApplicationSummaryDetailVO'
    productInfo.value.api = applicationSummaryDetailAddProduct
    productInfo.value.query.queryMap.productId.value = idNotIn.toString()
    productInfo.value.query.queryMap.orderId.value =
      formInfo.value.data.applicationId
  } else {
    productInfo.value.query.queryMap.id.value = idNotIn.toString()
    productInfo.value.query.queryMap.status.value = 1
    productInfo.value.query.queryParams.deptId = formInfo.value.data.deptId
  }
  productInfo.value.visible = true
}
function selectProductCallback(rows) {
  if (rows) {
    let selections = tableInfo.value.selectionsCopy
    rows = generateProductKey(rows)
    let purchType = formInfo.value.data.purchType
    if (purchType === 0 || purchType === 1) {
      const data = rows.map(function (item) {
        return {
          ...item,
          calcQty: item.calcQty - item.prePurchCalcQty,
          largeUnitQty: parseInt(
            (item.calcQty - item.prePurchCalcQty) / item.unitConvertCoefficient
          ),
          smallUnitQty: parseInt(
            (item.calcQty - item.prePurchCalcQty) % item.unitConvertCoefficient
          ),
          qty: 0,
          price: item.defaultSupplierPrice || 0,
          supplierId: item.defaultSupplierId,
          supplierName: item.defaultSupplierName,
        }
      })
      data.forEach((item) => {
        if (selections.length) {
          selections.forEach((row) => {
            if (row.productId === item.id) {
              item.maxConvertCount = row.maxConvertCount
              if (item.calcQty === 0) {
                item['largeUnitQty'] = parseInt(
                  (item.maxConvertCount || 0) / item.unitConvertCoefficient
                )
                item['smallUnitQty'] = parseInt(
                  (item.maxConvertCount || 0) % item.unitConvertCoefficient
                )
              }
            }
          })
        }
      })
      tableInfo.value.data = data.concat(tableInfo.value.data)
    } else {
      const data = rows.map(function (item) {
        return {
          ...item,
          qty: 0,
          price: item.price || 0,
          defaultSupplierId: item.supplierId,
          defaultSupplierName: item.supplierName,
          defaultSupplierCode: item.supplierCode,
          defaultSupplierPrice: item.price,
        }
      })
      data.forEach((item) => {
        if (selections.length) {
          selections.forEach((row) => {
            if (row.productId === item.id) {
              item.maxConvertCount = row.maxConvertCount
              if (item.calcQty === 0) {
                item['largeUnitQty'] = parseInt(
                  (item.maxConvertCount || 0) / item.unitConvertCoefficient
                )
                item['smallUnitQty'] = parseInt(
                  (item.maxConvertCount || 0) % item.unitConvertCoefficient
                )
              }
            }
          })
        }
      })
      tableInfo.value.data = data.concat(tableInfo.value.data)
    }
  }
}
function generateProductKey(products) {
  return products.map((item) => {
    const key =
      item.productId +
      '&' +
      item.batchNumber +
      '&' +
      item.validityDate +
      '&' +
      item.productionDate
    item._id = key
    return item
  })
}
//删除产品
function removeProduct() {
  proxy
    .$confirm('删除后将改变数据,是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      tableInfo.value.selectionsCopy = proxy.$fn.deepClone(
        tableInfo.value.selections
      )
      tableInfo.value.data = tableInfo.value.data.filter(
        (row) => !tableInfo.value.selections.includes(row)
      )
    })
}
//打开选择收货地址窗口
function openReceiveAddressWindow() {
  selectReceiveAddressInfo.value.visible = true
}
function selectReceiveAddressCallback(data) {
  if (data) {
    formInfo.value.data.receiveAddressValue = data.addressValue
    formInfo.value.data.receiveProvince = data.province
    formInfo.value.data.receiveCity = data.city
    formInfo.value.data.receiveCounty = data.county
    formInfo.value.data.receiveAddress = data.address
    formInfo.value.data.receiveAddressValue = data.addressValue
    formInfo.value.data.receiveContacts = data.contacts
    formInfo.value.data.receivePhone = data.contactsPhone
  }
}
function selectSupplierCallback(data) {
  if (data) {
    formInfo.value.data.supplierId = data.supplierId
    formInfo.value.data.supplierName = data.supplierName
    tableInfo.value.data = []
  }
}
function selectProductSupplierCallback(data) {
  tableInfo.value.data[selectProductSupplier.value.index] = {
    ...tableInfo.value.data[selectProductSupplier.value.index],
    supplierId: data.supplierId,
    supplierName: data.supplierName,
    price: data.price,
  }
}
//打开部门弹窗
function openDeptWindow() {
  selectDeptInfo.value.visible = true
}
function selectDeptCallback(data) {
  if (data) {
    if (formInfo.value.data.deptId !== data.id) {
      formInfo.value.data.deptName = data.name
      formInfo.value.data.deptId = data.id
      defaultSelect.value = []
      tableInfo.value.data = []
    }
  } else {
    formInfo.value.data.deptName = ''
    formInfo.value.data.deptId = ''
    defaultSelect.value = []
    tableInfo.value.data = []
  }
}
function save() {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    const details = tableInfo.value.data.map((item) => {
      return {
        ...item,
      }
    })
    const data = formInfo.value.data
    data.isSpecialEdit = props.isSpecialEdit
    data.sourceId = props.orderId
    data.sourceNo = props.useOrderNo
    data.sourceType = 2

    data.mergeDetails = details
    const api = data.id ? updatePurchOrder : createPurchOrder
    if (data.mergeDetails.length > 0) {
      api(data).then((resp) => {
        if (resp && resp.success) {
          // _proxy.$emit("returnModify", false);
          showDialog.value = false
          proxy.$router.push('/purch/order')
        }
      })
    } else {
      proxy.$message({
        duration: 3500,
        type: 'warning',
        showClose: true,
        message: '产品不能为空',
      })
    }
  })
}
function getPurchOrderById() {
  generatePurchOrderUseApplication(props.orderId).then((resp) => {
    if (resp && resp.success) {
      formInfo.value.data.deptId = resp.data.deptId
      formInfo.value.data.deptName = resp.data.deptName
      formInfo.value.data.isConsignBusinessValue =
        resp.data.isConsignBusinessValue
      formInfo.value.data.isConsignBusiness = resp.data.isConsignBusiness
      tableInfo.value.data = resp.data.mergeDetails
      if (tableInfo.value.data) {
        tableInfo.value.data.forEach((item) => {
          item['largeUnitQty'] = parseInt(
            (item.maxConvertCount || 0) / item.unitConvertCoefficient
          )
          item['smallUnitQty'] = parseInt(
            (item.maxConvertCount || 0) % item.unitConvertCoefficient
          )
        })
      }
    }
  })
}

function selectOrderChange(data) {
  if (data.length) {
    filterInfo.value.list[0]['disabled'] = true
    filterInfo.value.list[1]['disabled'] = true
    tableInfo.value.handle.btList[0]['show'] = false
    tableInfo.value.fieldList[6]['disabled'] = true
    disabledTemplateBtn.value = true
    defaultSelect.value = data
    let ids = data.map((item) => item.id).toString()
    mergedPurchIds.value = ids
    let params = {
      orderIdIn: ids,
    }
    getOrdersProduct(params).then((res) => {
      if (res) {
        tableInfo.value.data = res.data
      }
    })
  } else {
    filterInfo.value.list[0]['disabled'] = false
    filterInfo.value.list[1]['disabled'] = false
    tableInfo.value.handle.btList[0]['show'] = true
    disabledTemplateBtn.value = false
    tableInfo.value.fieldList[6]['disabled'] = false
    defaultSelect.value = []
    tableInfo.value.data = []
  }
}
function selectTemplate() {
  purchTemplateInfo.value.visible = true
  purchTemplateInfo.value.query.deptId = formInfo.value.data.deptId
  purchTemplateInfo.value.query.templateType = 0
}
function selectPurchTemplateCallback(data) {
  if (data) {
    let ids = data.map((row) => row.id)
    let purchTemplateIds = String(ids)
    const params = {
      purchTemplateIdIn: purchTemplateIds,
    }
    let selections = tableInfo.value.selectionsCopy
    getPurchTemplateDetailAll(params).then((resp) => {
      if (resp && resp.success) {
        resp.data = resp.data.filter((item) => {
          return tableInfo.value.data.every(
            (el) => el.productId !== item.productId
          )
        })
        resp.data.forEach((item) => {
          if (selections.length) {
            selections.forEach((row) => {
              if (row.productId === item.id) {
                item.maxConvertCount = row.maxConvertCount
                if (item.calcQty === 0) {
                  item['largeUnitQty'] = parseInt(
                    (item.maxConvertCount || 0) / item.unitConvertCoefficient
                  )
                  item['smallUnitQty'] = parseInt(
                    (item.maxConvertCount || 0) % item.unitConvertCoefficient
                  )
                }
              }
            })
          }
        })
        tableInfo.value.data = resp.data.concat(tableInfo.value.data)
      }
    })
  }
}
function getValueList() {
  getCoreSystemConfigGetConfigValue({
    systemConfigCode: 'license_nearly_effective',
  }).then((resp) => {
    if (resp && resp.success) {
      licencesSystemConfig.value = resp.data
    }
  })
}
function tableRowClassName({ row = undefined }) {
  if (row.licenseEndDate) {
    let dataDiff = proxy.$fn.dateDiffLicen(row.licenseEndDate)
    if (dataDiff <= 0) {
      return 'expire-row'
    } else if (Number(licencesSystemConfig.value) >= dataDiff) {
      return 'nearly-row'
    }
  }
  return ''
}
function getCustomize() {
  let param = {
    tableKey:
      'purchOrderDetailModify-com.slip.spd.entity.vo.purch.PurchOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      filterInfo.value.query.customizeUserVO = data
      filterInfo.value.query.queryMap.orderId.value = props.orderId

      if (props.orderId) {
        getPurchOrderById()
      }
    }
  })
}

let obj = {
  qty: {
    label: '申购数量',
    value: 'qty',
    type: 'slot',
    minWidth: '250px',
    hidden: true,
  },
  price: {
    label: '单价',
    value: 'price',
    type: 'slot',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('purchOrder:price'),
    hidden: true,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('purchOrder:price'),
    hidden: true,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    permission: !proxy.$permission('purchOrder:price'),
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
  },
}
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...obj,
})
getCustomize()

onMounted(() => {
  getValueList()
  formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
  //请求默认地址并回填
  getReceiveAddressPage({ isDefault: '1' }).then((resp) => {
    if (resp && resp.success && resp.data[0]) {
      formInfo.value.data.receiveProvince = resp.data[0].province
      formInfo.value.data.receiveCity = resp.data[0].city
      formInfo.value.data.receiveCounty = resp.data[0].county
      formInfo.value.data.receiveAddress = resp.data[0].address
      formInfo.value.data.receiveAddressValue = resp.data[0].addressValue
      formInfo.value.data.receiveContacts = resp.data[0].contacts
      formInfo.value.data.receivePhone = resp.data[0].contactsPhone
    }
  })
})
</script>

<style scoped lang="scss">
:deep(.table-scroll-hidden) > .el-table {
  overflow-y: hidden;
}
.model-panel-title {
  display: flex;
  align-items: center;
  .model-tips {
    display: flex;
    align-items: center;
    margin-left: 10px;
    color: #909399;
    .model-tips-nearly,
    .model-tips-expire {
      display: block;
      margin-left: 5px;
      width: 17px;
      height: 17px;
    }
    .model-tips-nearly {
      background: #fceacb;
    }
    .model-tips-expire {
      background: #f5e4e4;
    }
  }
}
:deep(.el-table) .nearly-row {
  background: #fceacb;
}
:deep(.el-table) .expire-row {
  background: #f5e4e4;
}
:deep(.el-table__body)
  tr.hover-row
  > td:not(.el-table-fixed-column--right, .el-table-fixed-column--left) {
  background-color: transparent !important;
}
</style>
